package com.fdq.bigevent.interceptor;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.fdq.bigevent.util.JwtUtil;
import com.fdq.bigevent.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/*
拦截器
拦截全部请求判断请求的jwt令牌是否有效
* */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //jwt码
        String token = request.getHeader("Authorization");
        //从jwt中解析出的数据
        Map<String, Object> claim = null;
        try{
            claim = JwtUtil.parseToken(token);
            //使用threadLocal保存用户信息
            ThreadLocalUtil.set(claim);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束后删除threadLocal中的信息
        ThreadLocalUtil.remove();
    }
}
